package com.trimer.rpc.core;

import com.trimer.rpc.core.config.RpcAnnotationScannerConfigurer;
import com.trimer.rpc.core.request.RpcRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class RpcHandler {
    @Autowired
    private RpcAnnotationScannerConfigurer rpcConfigurer;

    public Object handle(RpcRequest request) throws Exception {
        String serviceName = request.getServiceName();
        String serviceVersion = request.getServiceVersion();

        if (!StringUtils.isEmpty(serviceVersion)) {
            serviceName += "-" + serviceVersion;
        }

        Object serviceBean = rpcConfigurer.getRpcServiceBean(serviceName);
        if (null == serviceBean) {
            throw new RuntimeException(String.format("can not find service bean by key:%s", serviceName));
        }
        //获取反射调用所需要的参数
        Class<?> serviceClass = serviceBean.getClass();
        String methodName = request.getMethodName();
        Class<?>[] parameterTypes = request.getParamTypes();
        Object[] parameters = request.getParams();

        FastClass serviceFastClass = FastClass.create(serviceClass);
        FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
        return serviceFastMethod.invoke(serviceBean, parameters);
    }
}